import { defineStore } from "pinia";
import { ref } from "vue";
import { login as userLogin, getUserInfo } from "@/api/user";
import router from "@/router";
import { UserInfo } from "./types";

export const useUserStore = defineStore(
	"user",
	() => {
		// 用户信息
		const userInfo = ref<UserInfo | null>(null);

		// 登录状态
		const isLoggedIn = ref(!!localStorage.getItem("token"));

		// 登录
		const login = async (
			username: string,
			password: string
		): Promise<boolean> => {
			try {
				const res = await userLogin({ username, password });

				if (res.code === 200 && res.data.token) {
					// 保存token
					localStorage.setItem("token", res.data.token);
					// 更新登录状态
					isLoggedIn.value = true;
					// 更新用户信息
					userInfo.value = res.data.user;

					return true;
				}
				return false;
			} catch (error) {
				console.error("登录失败:", error);
				return false;
			}
		};

		// 获取用户信息
		const fetchUserInfo = async () => {
			if (!isLoggedIn.value) return;

			try {
				const res = await getUserInfo();
				if (res.code === 200 && res.data) {
					userInfo.value = res.data;
				}
			} catch (error) {
				console.error("获取用户信息失败:", error);
			}
		};

		// 退出登录
		const logout = () => {
			// 清除token
			localStorage.removeItem("token");
			// 清除用户信息
			userInfo.value = null;
			// 更新登录状态
			isLoggedIn.value = false;
			// 跳转到登录页
			router.push("/login");
		};

		return {
			userInfo,
			isLoggedIn,
			login,
			fetchUserInfo,
			logout,
		};
	},
	{
		persist: true,
	}
);
